package com.trkj.base.utils;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.trkj.base.Constants;
import com.trkj.base.OnLoginStatusListener;
import com.trkj.base.OnResponseResultListener;
import com.trkj.base.User;
import com.trkj.base.newwork.PostWaitingDataFromRemote;
import com.trkj.base.newwork.WaitingDataFromRemote;
import com.trkj.usercenter.LoginActivity;

/**
 * 用户服务
 * Created by LiZanhong on 2015/06/22.
 */
public class UserService {
    private Context context;
    private Base64String base64String;

    private static UserService userService;
    private static User user;

    /**
     * 单例
     * @param context
     * @return
     */
    public static UserService getInstance(Context context){
        if(userService == null){
            userService = new UserService(context);
        }
        return userService;
    }

    public UserService(Context context) {
        this.context = context;
        base64String = new Base64String();
    }

    /**
     * 从SharedPreferences中获取user信息
     *
     * @return
     */
    private String getUserJSON() {
        SharedPreferences sharedPreferences =
                PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPreferences.getString("user", null);
    }

    public User parseUser() {
        if(user != null) return user;

        return parseUser(getUserJSON());
    }

    /**
     * 解析出用户信息
     *
     * @return
     */
    public User parseUser(String userJson) {
        JSONObject jsonObject = JSON.parseObject(userJson);
        if(userJson == null) return null;

        User user = new User();
        user.userId = jsonObject.getIntValue("user_id");
        user.userName = jsonObject.getString("user_name");
        user.deptId = jsonObject.getIntValue("dept_id");
        user.sex = jsonObject.getString("sex");
        user.userType = jsonObject.getIntValue("user_type");
        user.avator = jsonObject.getString("avator");
        user.birthday = jsonObject.getString("birth");
        user.inDate = jsonObject.getString("in_date");
        user.endDate = jsonObject.getString("end_date");
        user.workCity = jsonObject.getString("work_city");
        user.trialPay = jsonObject.getDouble("trial_pay");
        user.pay = jsonObject.getDouble("pay");
        user.university = jsonObject.getString("university");
        user.address = jsonObject.getString("address");
        user.telephone = jsonObject.getString("telephone");
        user.qq = jsonObject.getString("qq");
        user.email = jsonObject.getString("email");
        user.deptName = jsonObject.getString("dept_name");

        return user;
    }

    /**
     * 保存用户信息
     *
     * @param userJsonStr
     */
    public void saveUser(String userJsonStr) {
        //保存
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("user", userJsonStr);
        editor.commit();
    }

    /**
     * 保存密码
     *
     * @param password
     */
    public void savePassword(String password) {
        String utf8String = Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
        Log.d("Base64", new String(Base64.decode(utf8String, Base64.DEFAULT)));
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("password", utf8String);
        editor.commit();
    }

    /**
     * 获取密码
     * @return
     */
    public String getPassword(){
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        return new String(Base64.decode(sp.getString("password", ""), Base64.DEFAULT));
    }

    /**
     * 保存用户信息
     *
     * @param userJson
     */
    public void saveUser(JSONObject userJson) {
        saveUser(userJson.toJSONString());
    }

    /**
     * 将头像解析出来
     *
     * @param user
     * @return
     */
    public Bitmap parseHeaderImage(User user) {
        String headerImage = user.avator;
        return base64String.stringToBitmap(headerImage);
    }

    /**
     * 判断是否登陆，找出保存的用户名密码，然后去服务器匹配一下
     * @return
     */
    public void isLogin(final OnLoginStatusListener loginStatusListener){
        SharedPreferences sharedPreferences
                = PreferenceManager.getDefaultSharedPreferences(context);
        User user = parseUser();
        String savedPassword = sharedPreferences.getString("password", null);

        //在1.0.7中消息推送需要以部门名称作为标签，如果部门名称为空，强制重新登陆
        if(null == user || null == savedPassword || user.deptName == null) {
            loginStatusListener.onLoginStatus(false);
            return;
        }


        if(null != user && null != savedPassword){
            String savedName = user.userName;
            WaitingDataFromRemote waitingDataFromRemote = new PostWaitingDataFromRemote(context);
            waitingDataFromRemote.setResponseResultListener(new OnResponseResultListener() {
                @Override
                public void onResponseResult(String result) {
                    //返回登陆状态
                    JSONObject jsonObject = JSON.parseObject(result);
                    loginStatusListener.onLoginStatus(jsonObject.getBoolean("success"));
                }
            });

            String param = "userName=" + savedName
                    + "&password=" + new String(Base64.decode(savedPassword, Base64.DEFAULT));


            waitingDataFromRemote.execute(Constants.ApiUrl.LOGIN, param);
        }else{
            loginStatusListener.onLoginStatus(false);
        }
    }

    /**
     * 判断是否登陆
     * @return
     */
    public void isLogin(){
        UserService.getInstance(context).isLogin(new OnLoginStatusListener() {
            @Override
            public void onLoginStatus(boolean flag) {
                if(flag){
                    //自动登陆成功

                }else{
                    //自动登陆失败，打开登录窗口
                    Intent intent = new Intent(LoginActivity.ACTION);
                    context.startActivity(intent);
                }
            }
        });
    };

    /**
     * 注销
     */
    public void logout(){
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove("user");
        editor.remove("password");
        editor.commit();
    }

}
